package cn.zptc.web;

import cn.zptc.dao.impl.FavoriteDaoImpl;
import cn.zptc.entity.Favorite;
import cn.zptc.entity.FavoriteCategory;
import cn.zptc.service.FavoriteService;
import cn.zptc.service.impl.FavoriteServiceImpl;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/client/getMyFavorites")
public class GetMyFavoritesServlet extends HttpServlet {

    private FavoriteService favoriteService;

    @Override
    public void init() throws ServletException {
        super.init();

        favoriteService = new FavoriteServiceImpl(new FavoriteDaoImpl());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //todo：先假定用户的id为i，以后从session取user对象进而获取id
        try {
            List<Favorite> favorites= favoriteService.getMyFavorites(1);
            //todo:先假定用户的id为i，以后从session取user对象进而获取id，获取用户在收藏中存在的分类
            List<FavoriteCategory> categories = favoriteService.getMyFavoriteCategorysInFavorite(1);
            Map<String,List<Favorite>> result = new HashMap<>();

            categories.forEach(category -> {
                List<Favorite> favoriteList = new ArrayList<>();
                favorites.forEach(favorite -> {
                    if (category.getId()==favorite.getCategoryId()){
                        favorite.setCategoryName(category.getCategoryName());
                        favoriteList.add(favorite);
                    }
                });
                result.put(category.getCategoryName(),favoriteList);
            });
            String jsonString = JSON.toJSONString(result);
            resp.setContentType("text/json;charset=UTF-8");
            resp.getWriter().write(jsonString);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
